<template>
  <div class="app-container">
    <div class="filter-container">
      <el-input v-model="listQuery.a1templatetableId" size="mini" placeholder="模板表ID" style="width: 200px; " class="filter-item" @keyup.enter.native="handleFilter" />
      <el-input v-model="listQuery.deleteflag" size="mini" placeholder="状态" style="width: 100px;" class="filter-item" @keyup.enter.native="handleFilter" />
      <el-button v-waves class="filter-item" size="mini" type="primary" icon="el-icon-search" @click="handleFilter">
        查询
      </el-button>
      <el-button class="filter-item" style="margin-left: 10px;" size="mini" type="primary" icon="el-icon-edit" @click="handleAutoAddColumnApi">
        自动同步数据库
      </el-button>
    </div>

    <el-table
      :key="tableKey"
      v-loading="listLoading"
      :data="list"
      border
      fit
      highlight-current-row
      style="width: 100%;"
      @sort-change="sortChange"
    >
      <el-table-column label="ID" prop="id" sortable="custom" align="center" width="80" :class-name="getSortClass('id')">
        <template slot-scope="{row}">
          <span>{{ row.id }}</span>
        </template>
      </el-table-column>
      <el-table-column label="columnname" width="120px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.columnname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="columnnamesql" width="120px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.columnnamesql" class="edit-input" size="mini" />
          <span v-else>{{ row.columnnamesql }}</span>
        </template>
      </el-table-column>
      <el-table-column label="columnshowname" width="120px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.columnshowname" class="edit-input" size="mini" />
          <span v-else>{{ row.columnshowname }}</span>
        </template>
      </el-table-column>
      <el-table-column label="columnnamesqlsum" width="120px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.columnnamesqlsum" class="edit-input" size="mini" />
          <span v-else>{{ row.columnnamesqlsum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="isfrozencolumn" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.isfrozencolumn" class="edit-input" size="mini" />
          <span v-else>{{ row.isfrozencolumn }}</span>
        </template>
      </el-table-column>
      <el-table-column label="needsum" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.needsum" class="edit-input" size="mini" />
          <span v-else>{{ row.needsum }}</span>
        </template>
      </el-table-column>
      <el-table-column label="sort" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.sort" class="edit-input" size="mini" />
          <span v-else>{{ row.sort }}</span>
        </template>
      </el-table-column>
      <el-table-column label="ishidden" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.ishidden" class="edit-input" size="mini" />
          <span v-else>{{ row.ishidden }}</span>
        </template>
      </el-table-column>
      <el-table-column label="isquery" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.isquery" class="edit-input" size="mini" />
          <span v-else>{{ row.isquery }}</span>
        </template>
      </el-table-column>
      <el-table-column label="canadd" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.canadd" class="edit-input" size="mini" />
          <span v-else>{{ row.canadd }}</span>
        </template>
      </el-table-column>

      <el-table-column label="column-type" width="120px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.columntype" class="edit-input" size="mini" />
          <span v-else>{{ row.columntype }}</span>
        </template>
      </el-table-column>
      <el-table-column label="is-sortcolumn" width="80px" align="left">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.issortcolumn" class="edit-input" size="mini" />
          <span v-else>{{ row.issortcolumn }}</span>
        </template>
      </el-table-column>
      <el-table-column label="options-sql" width="200px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.optionssql" class="edit-input" size="mini" />
          <span v-else>{{ row.optionssql }}</span>
        </template>
      </el-table-column>

      <el-table-column label="options-page" width="200px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.optionspage" class="edit-input" size="mini" />
          <span v-else>{{ row.optionspage }}</span>
        </template>
      </el-table-column>

      <el-table-column label="datare-source" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.dataresource" class="edit-input" size="mini" />
          <span v-else>{{ row.dataresource }}</span>
        </template>
      </el-table-column>

      <el-table-column label="table-alias-name" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.tablealiasname" class="edit-input" size="mini" />
          <span v-else>{{ row.tablealiasname }}</span>
        </template>
      </el-table-column>

      <el-table-column label="columnwidth" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.columnwidth" class="edit-input" size="mini" />
          <span v-else>{{ row.columnwidth }}</span>
        </template>
      </el-table-column>

      <el-table-column label="inputwidth4adddialog" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.inputwidth4adddialog" class="edit-input" size="mini" />
          <span v-else>{{ row.inputwidth4adddialog }}</span>
        </template>
      </el-table-column>
      <el-table-column label="linewidth4adddialog" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.linewidth4adddialog" class="edit-input" size="mini" />
          <span v-else>{{ row.linewidth4adddialog }}</span>
        </template>
      </el-table-column>
      <el-table-column label="required4adddialog" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.required4adddialog" class="edit-input" size="mini" />
          <span v-else>{{ row.required4adddialog }}</span>
        </template>
      </el-table-column>
      <el-table-column label="dataoptions4adddialog" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.dataoptions4adddialog" class="edit-input" size="mini" />
          <span v-else>{{ row.dataoptions4adddialog }}</span>
        </template>
      </el-table-column>
      <el-table-column label="style4adddialog" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.style4adddialog" class="edit-input" size="mini" />
          <span v-else>{{ row.style4adddialog }}</span>
        </template>
      </el-table-column>
      <el-table-column label="column_datatype" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.column_datatype" class="edit-input" size="mini" />
          <span v-else>{{ row.column_datatype }}</span>
        </template>
      </el-table-column>
      <el-table-column label="column_isnotnull" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.column_isnotnull" class="edit-input" size="mini" />
          <span v-else>{{ row.column_isnotnull }}</span>
        </template>
      </el-table-column>
      <el-table-column label="query_type" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.query_type" class="edit-input" size="mini" />
          <span v-else>{{ row.query_type }}</span>
        </template>
      </el-table-column>
      <el-table-column label="default_value" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.default_value" class="edit-input" size="mini" />
          <span v-else>{{ row.default_value }}</span>
        </template>
      </el-table-column>
      <el-table-column label="column_tip" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.column_tip" class="edit-input" size="mini" />
          <span v-else>{{ row.column_tip }}</span>
        </template>
      </el-table-column>
      <el-table-column label="data_transfer" width="80px" align="center">
        <template slot-scope="{row}">
          <el-input v-if="row.edit" v-model="row.data_transfer" class="edit-input" size="mini" />
          <span v-else>{{ row.data_transfer }}</span>
        </template>
      </el-table-column>

      <el-table-column label="创建日期" width="150px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.createdate | parseTime('{y}-{m}-{d} {h}:{i}') }}</span>
        </template>
      </el-table-column>

      <!--操作Button-->
      <el-table-column fixed="right" label="操作" align="center" min-width="200">
        <template slot-scope="{row,$index}">
          <el-button
            v-show="row.edit"
            type="success"
            size="mini"
            style="margin-left: 0px;"
            @click="cancelEdit(row)"
          >取消</el-button>

          <el-button
            v-if="row.edit"
            type="success"
            size="mini"
            style="margin-left: 0px;"
            @click="confirmEdit(row)"
          >保存</el-button>

          <el-button
            v-else
            type="primary"
            size="mini"
            style="margin-left: 0px;"
            @click="row.edit=!row.edit"
          >编辑</el-button>

          <el-popconfirm
            title="确认删除吗？"
            @onConfirm="handleDelete(row, $index)"
          >
            <el-button slot="reference" size="mini" type="danger">
              删除
            </el-button>
          </el-popconfirm>

        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />

  </div>
</template>

<script>
import { fetchList, updateApi, removeApi, autoAddColumnApi } from './tmpt-column-api'
import waves from '@/directive/waves' // waves directive
import { parseTime, deleteEmptyProperty } from '@/utils'
import Pagination from '@/components/Pagination' // secondary package based on el-pagination

export default {
  name: 'TmptColumnList',
  components: { Pagination },
  directives: { waves },
  filters: {
    statusFilter(status) {
      const statusMap = {
        published: 'success',
        draft: 'info',
        deleted: 'danger'
      }
      return statusMap[status]
    }
  },
  props: {
    a1templatetableId: Number
  },
  data() {
    return {
      tableKey: 0,
      list: null,
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        sort: '+id',
        deleteflag: 0,
        a1templatetableId: 0
      },
      importanceOptions: [1, 2, 3],
      sortOptions: [{ label: 'ID Ascending', key: '+id' }, { label: 'ID Descending', key: '-id' }],
      statusOptions: ['published', 'draft', 'deleted'],
      showReviewer: false,
      temp: {},
      dialogFormVisible: false,
      dialogForm4CodeVisible: false,
      dialogStatus: '',
      textMap: {
        update: 'Edit',
        create: 'Create'
      },
      rules: {
        name: [{ required: true, message: 'name is required', trigger: 'blur' }],
        loginname: [{ required: true, message: 'loginname is required', trigger: 'blur' }]
      },
      downloadLoading: false
    }
  },
  watch: {
    a1templatetableId(nval) {
      this.listQuery.a1templatetableId = nval
      this.getList()
    }
  },
  created() {
    this.listQuery.a1templatetableId = this.a1templatetableId
    this.getList()
  },
  methods: {
    getList() {
      this.listLoading = true
      deleteEmptyProperty(this.listQuery)
      fetchList(this.listQuery).then(result => {
        const items = result.map.rows
        this.total = result.map.total

        // 备份数据，编辑还原用
        this.list = items.map(v => {
          this.$set(v, 'edit', false) // https://vuejs.org/v2/guide/reactivity.html
          v.original = Object.assign({}, v)
          return v
        })

        // Just to simulate the time of the request
        setTimeout(() => {
          this.listLoading = false
        }, 0.1 * 1000)
      })
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
    },
    sortChange(data) {
      const { prop, order } = data
      if (prop === 'id') {
        this.sortByID(order)
      }
    },
    sortByID(order) {
      if (order === 'ascending') {
        this.listQuery.sort = '+id'
      } else {
        this.listQuery.sort = '-id'
      }
      this.handleFilter()
    },

    handleAutoAddColumnApi() {
      autoAddColumnApi({ _id: this.listQuery.a1templatetableId }).then(result => {
        if (result.success) {
          this.$notify({
            title: '成功',
            message: '扫库重新加载数据成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },

    cancelEdit(row) {
      // 还原原始值
      Object.keys(row).forEach(key => {
        if (key !== 'original' && key !== 'edit') {
          row[key] = row.original[key]
        }
      })
      row.edit = false
      // row.original.edit = false
      this.$message({
        message: '数据恢复到原始值',
        type: 'warning'
      })
    },

    confirmEdit(row) {
      const param = Object.assign({}, row)
      param.original = {}
      updateApi(param).then((result) => {
        if (result.success) {
          row.edit = false
          // 原始值：更新成最新输入仠
          Object.keys(row).forEach(key => {
            if (key !== 'original' && key !== 'edit') {
              row.original[key] = row[key]
            }
          })
          this.$notify({
            title: '成功',
            message: '数据更新成功',
            type: 'success',
            duration: 2000
          })
        }
      })
    },

    handleDelete(row, index) {
      removeApi({ id: '' + row.id }).then(() => {
        this.getList()
        this.$notify({
          title: '成功',
          message: '删除成功',
          type: 'success',
          duration: 2000
        })
      })
    },

    formatJson(filterVal) {
      return this.list.map(v => filterVal.map(j => {
        if (j === 'timestamp') {
          return parseTime(v[j])
        } else {
          return v[j]
        }
      }))
    },
    getSortClass: function(key) {
      const sort = this.listQuery.sort
      return sort === `+${key}` ? 'ascending' : 'descending'
    }
  }
}
</script>
<style>

</style>
